﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Json;
using System.Diagnostics;
using System.IO;

namespace FlickrWP7.Core
{
    public delegate void HelperDelegate();

    public static class Authentication
    {
        public static string Signature { get; set; }
        public static string FullToken { get; set; }

        private static HelperDelegate helperDelegateInstance;

        public static void GetSignature(Dictionary<string,string> parameters, string secret, HelperDelegate helperDelegate)
        {
            helperDelegateInstance = helperDelegate;
            Signature = null;

            string unHashed = secret;

            int counter = 0;
            string[] parameterNames = new string[parameters.Count];
            string[] parameterValues = new string[parameters.Count];

            foreach(string key in parameters.Keys)
            {
                parameterNames[counter] = key;
                parameterValues[counter] = parameters[key];
                counter++;
            }

            Array.Sort(parameterNames, parameterValues);

            for (int i = 0; i < parameterNames.Length; i++)
            {
                unHashed += parameterNames[i] + parameterValues[i];
            }

            MD5HashService.HashClient hashClient = new MD5HashService.HashClient();
            hashClient.GetHashStringCompleted += new EventHandler<MD5HashService.GetHashStringCompletedEventArgs>(hashClient_GetHashStringCompleted);
            hashClient.GetHashStringAsync(unHashed);

        }

        private static void hashClient_GetHashStringCompleted(object sender, MD5HashService.GetHashStringCompletedEventArgs e)
        {
            Signature = e.Result;
            helperDelegateInstance();
        }

        public static void GetFullToken (string miniToken, string signature,string apiKey, HelperDelegate helperDelegate)
        {
            helperDelegateInstance = helperDelegate;

            WebClient client = new WebClient();
            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
            string URL = string.Format("http://www.flickr.com/services/rest/?method=flickr.auth.getFullToken&api_key={0}&api_sig={1}&mini_token={2}&format=json",
                    apiKey, signature, miniToken);
            client.DownloadStringAsync(new Uri(URL));
        }

        private static void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            FullToken = e.Result;
            
            helperDelegateInstance();
        }
    }
}
